package com.xx.frame;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.JBColor;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 控件管理服务
 */
public class ComponentService {

    private static ComponentService service = new ComponentService();

    public static ComponentService getInstance() {
        return service;
    }

    private ComponentService() {

    }

    private MavenService mavenService = MavenService.getInstance();
    private NotifyService notifyService = NotifyService.getInstance();
    private CMDService cmdService = CMDService.getInstance();

    /**
     * 解析/刷新 按钮
     */
    public JButton buildParseButton(Project project, JPanel centerPanel, JPanel infoPanel) {
        JButton button = new JButton("解析/刷新");
        button.setFont(new Font("宋体", Font.BOLD, 12));
        button.setForeground(JBColor.BLUE);

        // 监听器逻辑
        ActionListener listener = e -> {
            List<String> allArtifactIds = MavenService.getInstance().getAllArtifactIds(project);

            // 展示信息
            NotifyService.getInstance().panelNotify(infoPanel, String.format("刷新时间：%s", System.currentTimeMillis()));

            // 清空内容
            centerPanel.removeAll();
            for (String artifactId : allArtifactIds) {
                JCheckBox checkBox = new JCheckBox(artifactId);
                centerPanel.add(checkBox);
            }
            centerPanel.updateUI();
        };
        button.addActionListener(listener);
        return button;
    }

    /**
     * 创建clean按钮
     */
    public JButton buildCleanButton(Project project, JPanel centerPanel, JPanel infoPanel) {
        JButton button = new JButton("clean");
        button.setFont(new Font("宋体", Font.BOLD, 12));
        button.setForeground(JBColor.BLUE);

        // 监听器逻辑
        ActionListener listener = e -> {

            // 判断是单个模块还是多个模块
            List<String> allArtifactIds = mavenService.getAllArtifactIds(project);
            // 多个模块
            if (Objects.nonNull(allArtifactIds)) {
                if (allArtifactIds.size() > 1) {
                    String cmd = "mvn clean \n";
                    cmdService.openTerminal(project, infoPanel, cmd);
                } else {
                    // 单个模块打包
                    cmdService.packageSingleProject(project, infoPanel, new ArrayList<>() {{
                        add("clean");
                    }});
                }
            } else {
                notifyService.panelNotify(infoPanel, "非maven项目或者配置错误");
            }
        };
        button.addActionListener(listener);
        return button;
    }

    /**
     * 创建打包按钮
     */
    public JButton buildPackageButton(String mcnCMD, String buttonName, Project project, JPanel configJPanel, JPanel centerPanel, JPanel infoPanel) {
        JButton button = new JButton(buttonName);
        button.setFont(new Font("宋体", Font.BOLD, 12));
        button.setForeground(JBColor.BLUE);

        // 监听器逻辑
        ActionListener listener = e -> {
            JTextField profileJTextField = (JTextField) getConfigComponentByName(configJPanel, DemoConstant.NAME_PROFILE);
            //JTextField threadsJTextField = (JTextField) getConfigComponentByName(configJPanel, DemoConstant.NAME_THREAD);

            // 保存当前的 profile
            String profile = profileJTextField.getText();
            profile = StringUtil.isEmpty(profile) ? DemoConstant.UAT : profile;
            PropertiesComponent.getInstance().setValue(DemoConstant.PROFILE_KEY, profile);

            /*String threads = threadsJTextField.getText();
            threads = StringUtil.isEmpty(threads) ? DemoConstant.DEFAULT_THREAD : threads;
            PropertiesComponent.getInstance().setValue(DemoConstant.THREAD_KEY, threads);*/

            // 判断是单个模块还是多个模块
            java.util.List<String> allArtifactIds = mavenService.getAllArtifactIds(project);
            List<String> rootArtifactId = mavenService.getRootArtifactId(project);


            // 当前项目有多个模块
            if (Objects.nonNull(allArtifactIds)) {

                // 是否选中了根 ArtifactId
                boolean rootSelected = false;
                if (allArtifactIds.size() > 1) {
                    StringBuilder info = new StringBuilder();
                    // 获得复选框
                    Component[] components = centerPanel.getComponents();
                    for (Component component : components) {
                        if (component instanceof JCheckBox) {
                            JCheckBox checkBox = (JCheckBox) component;
                            if (checkBox.isSelected()) {

                                // 判断是否选中了根 ArtifactId
                                if (rootArtifactId.contains(checkBox.getText().replace("/", ""))) {
                                    rootSelected = true;
                                }
                                info.append(checkBox.getText()).append(",");
                            }
                        }
                    }
                    notifyService.panelNotify(infoPanel, info.length() == 0 ? "未选中artifactId" : "已选择artifactId：" + info);

                    // 如果选中的包含了根pom ArtifactId,则全部打包
                    if (rootSelected || info.length() == 0) {

                        /*cmdService.packageSingleProject(project, infoPanel, new ArrayList<>() {{
                            add("clean");
                            add("package");
                        }});*/

                        // 不选则全部打包
                        String cmd = "%s clean package -P%s -DskipTests \n";
                        cmdService.openTerminal(project, infoPanel, String.format(cmd, mcnCMD, profile));
                    } else if (info.length() > 0) {
                        //String cmd = "%s clean package -pl %s -am -P%s --threads %sC -DskipTests \n";
                        //cmdService.openTerminal(project, infoPanel, String.format(cmd, mcnCMD, info, profile, threads));
                        String cmd = "%s clean package -pl %s -am -P%s -DskipTests \n";
                        cmdService.openTerminal(project, infoPanel, String.format(cmd, mcnCMD, info, profile));
                    }
                } else {

                    // 当前项目有只有单个模块
                    cmdService.packageSingleProject(project, infoPanel, new ArrayList<>() {{
                        add("clean");
                        add("package");
                    }});
                }
            } else {
                notifyService.panelNotify(infoPanel, "非maven项目或者配置错误");
            }
        };

        button.addActionListener(listener);
        return button;
    }

    /**
     * 根据name 找组件
     */
    private Component getConfigComponentByName(JPanel configJPanel, String name) {
        List<Component> allComponents = Util.getAllComponents(configJPanel);
        return allComponents.stream().filter(c -> Objects.equals(c.getName(), name)).findAny().orElse(null);
    }

    /**
     * profile输入框等配置
     */
    public void addConfigField(JPanel configJPanel, Project project, JPanel centerPanel, JPanel infoPanel) {
        // https://blog.csdn.net/kfepiza/article/details/134702862    参考 GridBagConstraints
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.WEST;


        c.gridx = 0;
        c.gridy = 0;
        addConfigButton(this.buildGitPushButton(project, infoPanel), c, configJPanel);

        c.gridx = 0;
        c.gridy = 1;
        addProfileComponent(c, configJPanel);

        c.gridx = 0;
        c.gridy = 2;
        addConfigButton(this.buildParseButton(project, centerPanel, infoPanel), c, configJPanel);

        c.gridx = 0;
        c.gridy = 3;
        addConfigButton(this.buildCleanButton(project, centerPanel, infoPanel), c, configJPanel);

        c.gridx = 0;
        c.gridy = 4;
        addConfigButton(this.buildPackageButton("mvn", "package mvn", project, configJPanel, centerPanel, infoPanel), c, configJPanel);

        c.gridx = 0;
        c.gridy = 5;
        addConfigButton(this.buildPackageButton("mvnd", "package mvnd", project, configJPanel, centerPanel, infoPanel), c, configJPanel);
    }

    private void addProfileComponent(GridBagConstraints c, JPanel configJPanel) {
        // profile 配置
        JLabel label = new JLabel("profile:");
        JTextField textField = new JTextField(DemoConstant.DEFAULT_COLUMN);
        textField.setName(DemoConstant.NAME_PROFILE);
        String defaultProfile = PropertiesComponent.getInstance().getValue(DemoConstant.PROFILE_KEY);
        textField.setText(StringUtil.isEmpty(defaultProfile) ? DemoConstant.UAT : defaultProfile);

        JPanel rowPanel = new JPanel();
        rowPanel.add(label);
        rowPanel.add(textField);
        configJPanel.add(rowPanel, c);
    }

    private JButton buildGitPushButton(Project project, JPanel infoPanel) {
        JButton button = new JButton("git push --force-with-lease");
        button.setFont(new Font("宋体", Font.BOLD, 12));
        button.setForeground(JBColor.RED);

        button.addActionListener(e -> {
            // 弹出确认对话框
            int option = JOptionPane.showConfirmDialog(
                    infoPanel,
                    "确定要执行此操作吗？",
                    "操作确认",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE
            );

            // 如果用户点击了"是"(YES_OPTION)
            if (option == JOptionPane.YES_OPTION) {
                String cmd = "git push --force-with-lease \n";
                cmdService.openTerminal(project, infoPanel, cmd);
            }
        });
        return button;
    }

    private void addConfigButton(JButton button, GridBagConstraints c, JPanel configJPanel) {
        JPanel rowPanel = new JPanel();
        rowPanel.add(button);
        configJPanel.add(rowPanel, c);
    }
}
